/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package headquarters;

import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import headquarters.statistics.Car;
import headquarters.statistics.Position;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.jms.JMSException;
import javax.jms.TextMessage;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;


/**
 *
 * @author Marcin Bełzowski
 * Parsuje message przesłanego przez samochód i utrwala w bazie danych
 */
@Stateless
public class CarInfoDateBean implements CarInfoDateLocal {
    @PersistenceContext private EntityManager entityManager;
    
    /*
     *idGPS x y date
     *Long double double GregorianCalendar
     *
     */
   
    public Boolean parse(TextMessage msg) {
        try {
            String textToParser = msg.getText();
            Car car;
            Position p;
            String[] tmp = textToParser.split("\\s+");
            long idGps;
            double x;
            double y;
            int yr,mt,d,h,m,s;
            idGps = Long.parseLong(tmp[0]);
            x = Double.parseDouble(tmp[1]);
            y = Double.parseDouble(tmp[2]);
            yr = Integer.parseInt(tmp[3]); mt = Integer.parseInt(tmp[4]); d = Integer.parseInt(tmp[5]); h = Integer.parseInt(tmp[6]);
            m = Integer.parseInt(tmp[7]);
            s = Integer.parseInt(tmp[8]);
            car = new Car(idGps);
            Calendar cal = new GregorianCalendar(yr,mt,d,h,m,s);

            GeometryFactory geometryFactory = new GeometryFactory();
            WKTReader reader = new WKTReader(geometryFactory);
            try {
                Point point = (Point) reader.read("POINT("+x+" "+y+")");
                point.setSRID(4326);
                 p = new Position(point,cal );

            
            car.setPositions(p);

            entityManager.persist(car);
            return true;
            } catch (ParseException ex) {
                Logger.getLogger(CarInfoDateBean.class.getName()).log(Level.SEVERE, null, ex);
                return false;
            }

           
        } catch (JMSException ex) {
            
            Logger.getLogger(CarInfoDateBean.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    
}
